package com.chenshu.demo.controller;

import com.chenshu.demo.model.User;
import com.chenshu.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-23
 * Time：20:18
 */
@RestController
@RequestMapping("/user")
public class UserController{
    @Autowired
    private UserService userService;
    @Autowired
    DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    TransactionDefinition transactionDefinition;

    @RequestMapping("/getall")
    public List<User> getUsers() {
        System.out.println("执行了 UserController.getUsers 方法");
        return userService.getAll();
    }

    //1、编程式事务
    @RequestMapping("/add")
    public int add(String username, String password, String gitUrl) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return 0;
        }

        //得到并开启事务
        TransactionStatus transactionStatus =
                dataSourceTransactionManager.getTransaction(transactionDefinition);

        int ret = userService.add(username, password, gitUrl);
        System.out.println("影响行数：" + ret);

        //回滚事务 or 提交事务
        //dataSourceTransactionManager.rollback(transactionStatus);
        dataSourceTransactionManager.commit(transactionStatus);
        return ret;
    }

    //声明式事务
    @RequestMapping("/add2")
    @Transactional
    public int add2(String username, String password, String gitUrl) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return 0;
        }

        int ret = userService.add(username, password, gitUrl);
        System.out.println("影响行数：" + ret);
        //测试是否回滚
        try{
            int num = 10/0;
        } catch (Exception e) {
            System.out.println("程序出现异常" + e.getMessage());
            //回滚方式有两种：1、下面这种 2、自行抛出异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ret;
    }
}
